<template>
  <div class="base-container" id="main">
    <div style="display: flex;font-weight: bold;color: #000000;justify-content: center;font-size: 29px;padding: 20px">
      江西省地方标准
    </div>
    <div
      style="display: flex;font-weight: bold;color: #000000;justify-content: center;font-size: 21px;margin-bottom: 10px;">
      项目申报表
    </div>
    <div
      style="display: flex;font-weight: bold;color: #000000;justify-content: center;font-size: 21px;margin-bottom: 10px;">
      （试行）
    </div>
    <t-form labelAlign="top" ref="form" :data="formData" :rules="rules" class="step-form table-form"
            labelWidth="140px">
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>项目名称</t-col>
        <t-col :span="4">
                    <t-form-item name="projectName">
                      <t-input clearable v-model="formData.projectName"></t-input>
                    </t-form-item>
        </t-col>
        <t-col :span="2" class="title"><span class="require">*</span>提出日期</t-col>
        <t-col :span="4">
                    <t-form-item name="putDate">
                      <t-date-picker style="width: 390px" clearable v-model="formData.putDate"></t-date-picker>
                    </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">技术归口单位</t-col>
        <t-col :span="4">
          标准委员会
        </t-col>
        <t-col :span="2" class="title">中文名称</t-col>
        <t-col :span="4">
          <!--          <t-form-item name="projectName">-->
          <!--            <t-input clearable v-model="formData.projectName"></t-input>-->
          {{ formData.projectName }}
          <!--          </t-form-item>-->
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>英文名称</t-col>
        <t-col :span="10">
          <t-form-item name="englishName">
            <t-input clearable v-model="formData.englishName"></t-input>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>标准性质</t-col>
        <t-col :span="10">
          <t-form-item name="standardProperty">
            <t-radio-group clearable v-model="formData.standardProperty"
                           :options="dict.type.standard_property">
            </t-radio-group>
          </t-form-item>
        </t-col>
        <!-- <t-col :span="2" class="title"><span class="require">*</span>批复立项时间</t-col>
        <t-col :span="4">
          <t-form-item name="replyDate">
            <t-date-picker style="width: 390px" clearable v-model="formData.replyDate">
            </t-date-picker>
          </t-form-item>
        </t-col> -->
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>制定/修订</t-col>
        <t-col :span="4">
          <t-form-item name="formulateType">
            <t-radio-group clearable v-model="formData.formulateType"
                           :options="dict.type.formulate_type">
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="2" class="title"><span class="require"
                                             v-if="formData.formulateType && formData.formulateType!=='1'">*</span>被修订标准号
        </t-col>
        <t-col :span="4">
          <t-form-item v-if="formData.formulateType && formData.formulateType!=='1'" name="formulateType">
            <t-input clearable v-model="formData.reviseNum"></t-input>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>采标情况</t-col>
        <t-col :span="10" style="display:block;">
          <t-row>
            <t-col :span="2" class="sub-title"><span class="require">*</span>（1）采用国际标准：</t-col>
            <t-col :span="10">
              <t-form-item name="bidCondition.bidType">
                <t-radio-group clearable v-model="formData.bidCondition.bidType"
                               :options="dict.type.bid_type">
                </t-radio-group>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title"><span class="require" v-if="formData.bidCondition.bidType!=='1'">*</span>（2）采用程度：</t-col>
            <t-col :span="10">
              <t-form-item v-if="formData.bidCondition.bidType!=='1'" name="bidCondition.bidDegree">
                <t-radio-group clearable v-model="formData.bidCondition.bidDegree"
                               :options="dict.type.bid_degree">
                </t-radio-group>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title"><span class="require" v-if="formData.bidCondition.bidType!=='1'">*</span>（3）采标名称：</t-col>
            <t-col :span="10">
              <t-form-item v-if="formData.bidCondition.bidType!=='1'" name="bidCondition.bidName">
                <t-input clearable v-model="formData.bidCondition.bidName"></t-input>
              </t-form-item>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="2" class="sub-title"><span class="require" v-if="formData.bidCondition.bidType!=='1'">*</span>（4）采 标 号：</t-col>
            <t-col :span="10">
              <t-form-item v-if="formData.bidCondition.bidType!=='1'" name="bidCondition.bidNum">
                <t-input clearable v-model="formData.bidCondition.bidNum"></t-input>
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title">项目周期</t-col>
        <t-col :span="10">
          12个月
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>起草单位</t-col>
        <t-col :span="10">
          <standard-company ref="standard-company" tableSize="small" v-model="formData.draftUnits"
                            :editOpen="true"></standard-company>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>技术归口单位 （或技术委员会）</t-col>
        <t-col :span="10">
          标准委员会
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>主管部门</t-col>
        <t-col :span="10">
          <t-tree-select clearable filterable :treeProps="{ keys: { value: 'id' } }"
                         v-model="formData.manageDeptId" :data="deptMenuOptions" placeholder="选择主管部门"></t-tree-select>
        </t-col>
      </t-row>

      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>制修订地方标准的必要性、可行性
          <t-tooltip
            content="【立项必要性包括但不限于：经济社会和产业发展的需求；相关法律法规、政策规划的要求；标准实施后重大经济、社会、生态效益分析。项目可行性包括但不限于：产业发展情况；有关技术的成熟度和经济性分析；如果实施标准对企业生产经营成本影响较大，应进行综合成本分析；已经具备的研究基础和条件等】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip>
        </span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="necessity">

            <tiny-mce-editor key="necessity" v-model="formData.necessity"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>主要技术内容
          <t-tooltip content="【包括范围和主要技术内容等，修订项目应说明拟修订的内容，与原标准相比的主要变化。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="technicalContent">

            <tiny-mce-editor key="technicalContent"
                             v-model="formData.technicalContent"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span>
          <span>国内外标准情况、与国际标准一致性程度情况<t-tooltip
            content="【包括国内相关标准情况，与拟制定标准的关系，范围包含但不限于相关国家标准、行业标准、地方标准、团体标准和企业标准；有关国际标准化组织、有关国家或地区的相关标准情况、主要内容；拟制定标准拟采用或参照哪些国际国外标准，并对一致性进行描述。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="description">

            <tiny-mce-editor key="description"
                             v-model="formData.description"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>与相关强制性标准、法律法规配套情况
          <t-tooltip content="【包括国内有关强制性标准、法律法规情况，与拟制定标准的关系。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="relation">

            <tiny-mce-editor key="relation"
                             v-model="formData.relation"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>

      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>标准所涉及的产品、过程或者服务目录
          <t-tooltip content="【应尽可能详细列出所规范的产品、过程或服务的名称或清单。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="catalogue">

            <tiny-mce-editor key="catalogue"
                             v-model="formData.catalogue"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>

      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>可能涉及的相关知识产权情况
          <t-tooltip content="【应尽可能列出可能涉及的知识产权情况，包括采用其他标准涉及的版权情况，标准涉及专利情况等。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <!-- <t-col :span="12" class="title"><span class="textTips-color-red">如果遇到格式问题，请先将内容复制到word中调整好，再黏贴到系统中</span></t-col> -->
          <t-form-item name="intellectual">

            <tiny-mce-editor key="intellectual"
                             v-model="formData.intellectual"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>

      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>征求省有关部门或省级专业标准化技术委员会意见的情况
          <t-tooltip content="【标准化对象如涉及省有关部门或省级专业标准化技术委员会，应征求并提供相关部门（省级专业标准化技术委员会）的意见。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="idea">

            <tiny-mce-editor key="idea"
                             v-model="formData.idea"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>经费预算
          <t-tooltip content="【应包括制定标准所需经费总额、政府补助经费、自筹经费的情况。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="budget">

            <tiny-mce-editor key="budget"
                             v-model="formData.budget"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>

      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>项目进度安排
          <t-tooltip content="【标准进度一般按照标准制修订程序的各个阶段进行，应制定详细的工作计划，根据制修订周期细化组织起草、征求意见、技术审查等各阶段具体时间安排。】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="schedule">

            <tiny-mce-editor key="schedule"
                             v-model="formData.schedule"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>

      <t-row style="min-height: 200px">
        <t-col :span="2" class="title"><span class="require">*</span><span>需要申报的其他事项
          <t-tooltip content="【需要废止或修订其他标准的建议，以及其他需要说明的事项】">
            <t-icon name="help-circle-filled"></t-icon>
          </t-tooltip></span>
        </t-col>
        <t-col :span="10">
          <t-form-item name="other">

            <tiny-mce-editor key="other" v-model="formData.other"></tiny-mce-editor>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>相关附件</t-col>
        <t-col :span="10">
          <t-table size="small" row-key="id" :columns="projectFileColumns" :data="projectFileData">
            <template #id="{row, rowIndex}">
              {{ rowIndex + 1 }}
            </template>
            <template #op="{row}">
              <file-upload v-model="row.fileIds" :moduleKey="row.moduleKey"
                           :fileList="row.fileLists"
                           :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{row}">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-col>
      </t-row>
    </t-form>
    <t-row style="margin-top: 20px;text-align: center">
      <t-col :span="12">
        <t-space :size="10">
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
              applyLoading ? '提交中...' : '暂存'
            }}
          </t-button>
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
              applyLoading ? '提交中...' : '提交'
            }}
          </t-button>
        </t-space>
      </t-col>
    </t-row>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import standardCompany from "@/pages/bzh/standard/components/standard-company.vue";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";

import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"


export default {
  name: "suggest-apply",
  dicts: ['standard_property', 'formulate_type', 'bid_type', 'bid_degree', 'yes_or_not'],
  components: {
    standardCompany,
    TinyMceEditor,
    FileUpload,
  },
  data() {
    return {
      file_domain: VITE_FILE_DOMAIN,
      projectFileData: [
        // {
        //   id: 1,
        //   c1: "立项公文（盖章原件）",
        //   c2: "是",
        //   moduleKey: "projectLXGW",
        //   fileIds: [],
        //   fileLists: [],
        //   require: true,
        // },
        {
          id: 1,
          c1: "标准草案",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBZCA",
          require: true,
        },
        {
          id: 2,
          c1: "编制说明",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBZSM",
          require: true,
        },
        {
          id: 3,
          c1: "其他",
          c2: "否",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectOther",
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      deptMenuOptions: [],
      formData: {
        localId: null,
        projectName: '',
        // replyDate: '',
        englishName: '',
        putDate: '',
        standardProperty: '1',
        formulateType: '1',
        reviseNum: '',
        manageDeptId: 100,
        bidCondition: {
          bidType: '1',
          bidDegree: '',
          bidName: '',
          bidNum: '',
        },
        linkMan: '',
        linkWay: '',
        draftUnits: [],
        necessity: '',
        technicalContent: '',
        description: '',
        relation: '',
        catalogue: '',
        intellectual: '',
        idea: '',
        budget: '',
        schedule: '',
        other: '',
      },
      rules: {
        projectName: [
          {
            required: true,
            message: "项目名称不能为空",
          }
        ],
        putDate: [
          {
            required: true,
            message: "提出日期不能为空",
          }
        ],
        englishName: [
          {
            required: true,
            message: "英文名称不能为空",
          }
        ],
        standardProperty: [
          {
            required: true,
            message: "标准性质不能为空",
          }
        ],
        formulateType: [
          {
            required: true,
            message: "制定/修订不能为空",
          }
        ],
        reviseNum: [
          {
            required: true,
            message: "被修订标准号不能为空",
          }
        ],
        manageDeptId: [
          {
            required: true,
            message: "主管部门不能为空",
          }
        ],
        // linkMan: [
        //   { required: true, message: "联系人姓名不能为空"}
        // ],
        // linkWay: [
        //   {
        //     required: true,
        //     message: "联系人电话不能为空",
        //   },
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: "联系人电话请输入正确的手机号码",
        //   },
        // ],
        // aim: [
        //   {
        //     required: true,
        //     message: "目的意义不能为空",
        //   }
        // ],
        draftUnits: [{required: true, validator: (val) => val && val.length, message: "起草单位不能为空", type: "error"}],
        'bidCondition.bidType': [
          {
            required: true,
            message: "采标情况-采用国际标准不能为空",
          }
        ],
        'bidCondition.bidDegree': [
          {
            required: true,
            message: "采标情况-采用程度不能为空",
          }
        ],
        'bidCondition.bidName': [
          {
            required: true,
            message: "采标情况-采标名称不能为空",
          }
        ],
        'bidCondition.bidNum': [
          {
            required: true,
            message: "采标情况-采标号不能为空",
          }
        ],
        necessity: [
          {
            required: true,
            message: "制修订地方标准的必要性、可行性不能为空",
          }
        ],
        technicalContent: [
          {
            required: true,
            message: "主要技术内容不能为空",
          }
        ],
        description: [
          {
            required: true,
            message: "国内外标准情况、与国际标准一致性程度情况不能为空",
          }
        ],
        relation: [
          {
            required: true,
            message: "与相关强制性标准、法律法规配套情况不能为空",
          }
        ],
        catalogue: [
          {
            required: true,
            message: "标准所涉及的产品、过程或者服务目录不能为空",
          }
        ],
        intellectual: [
          {
            required: true,
            message: "可能涉及的相关知识产权情况不能为空",
          }
        ],
        idea: [
          {
            required: true,
            message: "征求省有关部门或省级专业标准化技术委员会意见的情况不能为空",
          }
        ],
        budget: [
          {
            required: true,
            message: "经费预算不能为空",
          }
        ],
        schedule: [
          {
            required: true,
            message: "项目进度安排不能为空",
          }
        ],
        other: [
          {
            required: true,
            message: "需要申报的其他事项不能为空",
          }
        ],
        // projectUp: [
        //   {
        //     required: true,
        //     message: "是否有科研项目支撑不能为空",
        //   }
        // ],
        // projectUpInfos: [{required: true, validator: (val) => val && val.length, message: "科研项目编号及名称不能为空", type: "error"}],
        // parentUp: [{required: true, message: "是否涉及专利不能为空",}],
        // parentUpInfos: [{required: true, validator: (val) => val && val.length, message: "专利号及名称不能为空", type: "error"}],
      },
      applyLoading: false,
    }
  },
  created() {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("缺少id");
      this.close();
      return false;
    }
    this.getDeptTreeSelect();
    this.formData.localId = taskId
    // 先获取申报表详情
    this.$api.bzh.standard.getApplyBySuggestId(taskId).then(response => {
      if (!response.data) {
        this.$api.bzh.standard.getSuggest(taskId).then(res => {
          if (!res.data) {
            return false;
          }
          this.formData = { ...this.formData, ...res.data}
          this.formData.necessity = res.data.aim
          this.formData.technicalContent = res.data.radius

          // 删除建议表ID
          if (Object.prototype.hasOwnProperty.call(this.formData, "id")) {
            this.formData.id = null;
          }
        }).catch(e => {
          this.$message.error(e.toString())
        })
      } else {
        this.formData = { ...this.formData, ...response.data}
        getFiles(response.data.id).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val, index) => {
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
      if (!this.formData.bidCondition) {
        this.formData.bidCondition = {}
      }
    }).catch(e => {
      this.$message.error(e.toString())
    })
  },
  methods: {
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val=>{
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        this.$refs.form.validate({
          fields: ['projectName']
        }).then((validateResult) => {
          if (validateResult === true) {
            this.applyLoading = true;
            if (!this.formData.id) {
              this.$api.bzh.standard.addApply({
                ...this.formData,
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.formData.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.bzh.standard.updateApply({
                ...this.formData,
                sysAttMainVo: {
                  sysAttMainIds
                }
              }).then(response => {
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            const isValidate = this.$refs["standard-company"].checkData()
            if (!isValidate) {
              return false
            }
            const isValidate2 = this.projectFileData.every(val => {
              if (val.require && val.fileIds.length <= 0) {
                this.$message.error(`需要上传${val.c1}`);
                return false;
              }
              return true
            })
            if (!isValidate2) {
              return false
            }

            const confirmDia = this.$dialog.confirm({
              header: "提交后不可再编辑，会自动进入到下一阶段",
              body: `是否确认提交？`,
              theme: "warning",
              onConfirm: ({e}) => {
                confirmDia.update({
                  confirmBtn: {
                    loading: true,
                  },
                })
                this.applyLoading = true;
                this.$api.bzh.standard.submitApply({
                  ...this.formData,
                  sysAttMainVo: {
                    sysAttMainIds
                  }
                }).then(response => {
                  this.applyLoading = false;
                  confirmDia.destroy();
                  this.$message.success('提交成功');
                  this.close();
                }).catch((e) => {
                  confirmDia.update({
                    confirmBtn: {
                      loading: false,
                    },
                  })
                  this.applyLoading = false;
                  this.$message.error(e.toString());
                });
              },
            })



          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    },
    close() {
      this.$tab.closeOpenPage({path: "/bzh/apply/apply-my"});
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-table__empty {
  min-height: initial;
}
</style>
